<template>
  <div class="loginwrapper">
    <div class="login-form">
      <div class="flexbetween">
        <img src="@/assets/images/logo.png" alt="" class="logo" />
        <div class="f-14 c_primary commhover" @click="handlePage('/login')">返回登录</div>
      </div>
      <div class="login_body">
        <div class="f-18 mb-20 logintitle">账号注册</div>
        <el-form
          ref="loginForm"
          :model="loginForm"
          :rules="loginRules"
          class="loginform"
        >
          <el-form-item prop="phone">
            <el-input
              v-model="loginForm.phone"
              type="text"
              auto-complete="off"
              placeholder="输入您的手机号"
            >
              <svg-icon
                slot="prefix"
                icon-class="phone"
                class="el-input__icon input-icon"
              />
            </el-input>
          </el-form-item>
          <el-form-item prop="code" class="yzmitem">
            <el-input
              v-model="loginForm.code"
              type="text"
              auto-complete="off"
              placeholder="输入短信验证码"
            >
              <svg-icon
                slot="prefix"
                icon-class="yzmcode"
                class="el-input__icon input-icon"
              />
              <template slot="append">
                <span class="c_primary commhover" v-if="code == '获取验证码'" @click="getYzm">{{code}}</span>
                <span v-else>{{code}}</span>
              </template>
            </el-input>
            <el-tooltip class="item" effect="dark" placement="top-start">
              <div slot="content" class="f-14">1、请检查是否被软件拦截<br/>2、请核实是否已欠费停机<br/>3、如果手机已经丢失或停用，请联系<br/>我们客服QQ或电话400-998-1236</div>
              <span class="reg_tips">收不到短信？</span>
            </el-tooltip>
            <!-- <span class="reg_tips">收不到短信？</span> -->
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              auto-complete="off"
              placeholder="设置至少6位的密码"
              @keyup.enter.native="handleLogin"
            >
              <svg-icon
                slot="prefix"
                icon-class="pwd"
                class="el-input__icon input-icon"
              />
            </el-input>
          </el-form-item>
          <el-form-item prop="repassword">
            <el-input
              v-model="loginForm.repassword"
              type="password"
              auto-complete="off"
              placeholder="再次输入已确认密码"
              @keyup.enter.native="handleLogin"
            >
              <svg-icon
                slot="prefix"
                icon-class="pwd"
                class="el-input__icon input-icon"
              />
            </el-input>
          </el-form-item>
          <el-form-item style="width: 100%">
            <el-button
              :loading="loading"
              size="large"
              type="primary"
              class="f-16 w_full loginbtn"
              @click.native.prevent="handleLogin"
            >
              <span v-if="!loading">提交注册</span>
              <span v-else>注 册 中...</span>
            </el-button>
          </el-form-item>
          <div class="checkbox flexbetween mb-20">
            <el-checkbox v-model="loginForm.rememberMe">我已阅读并接受<span class="c_primary">《用户协议》</span></el-checkbox>
          </div>
          <div class="other_top f-14 c_000">
            <span class="other_text">第三方登录</span>
          </div>
          <div class="flexcenter othericon mt-15">
            <img src="@/assets/images/wechat.png" class="commhover mr-20"  @click="handlePage('/login')" />
            <img src="@/assets/images/qq.png" alt="" class="commhover" />
          </div>
        </el-form>
      </div>
    </div>
    <!--  底部  -->
    <div class="el-login-footer mt-20">
      <span class="c_999 f-14"
        >Copyright © 2023-现在 湖南锐行科技有限公司 All Rights Reserved 湘ICP备
        14031293号-1</span
      >
    </div>
  </div>
</template>

<script>
import WxcodeLogin from "./WxcodeLogin.vue";
import AccountLogin from "./AccountLogin.vue";
import { getCodeImg } from "@/api/login";
import Cookies from "js-cookie";
import { validPhone } from "@/utils/validate";
import { encrypt, decrypt } from "@/utils/jsencrypt";

export default {
  name: "Login",
  data() {
    const equalToPassword = (rule, value, callback) => {
      if (this.loginForm.password !== value) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };
    return {
      active: 1,
      codeUrl: "",
      loginForm: {
        phone: "",
        password: "",
        repassword:'',
        rememberMe: false,
        code: "",
        uuid: "",
      },
      loginRules: {
        phone: [{ required: true, trigger: "blur", validator: validPhone }],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" },
          { min: 6, max: 20, message: '用户密码长度必须介于 6 和 20 之间', trigger: 'blur' }
        ],
        repassword: [
          { required: true, trigger: "blur", message: "请再次输入您的密码" },
          { required: true, validator: equalToPassword, trigger: "blur" }
        ],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }],
      },
      code:'获取验证码',
      isLoading:false,
      loading: false,
      // 验证码开关
      captchaEnabled: true,
      // 注册开关
      register: false,
      redirect: undefined,
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  components: {
    WxcodeLogin,
    AccountLogin,
  },
  created() {
    // this.getCookie();
  },
  methods: {
    handleSelect(type) {
      this.active = type;
    },

    getCode() {
      getCodeImg().then((res) => {
        this.captchaEnabled =
          res.captchaEnabled === undefined ? true : res.captchaEnabled;
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.loginForm.uuid = res.uuid;
        }
      });
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get("rememberMe");
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password:
          password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
      };
    },

    //获取验证码
    getYzm() {
      // 防止重复点击
      if(this.isLoading) return
      this.isLoading=true;
      this.codeEvent(this.loginForm.phone);
      setTimeout(()=>{
        this.isLoading=false;
      },1000)
    },
    //封装验证码的函数
    codeEvent(iphone) {
      console.log(iphone);
      let reg = /^1[0-9]{10}$/;
      if (!reg.test(iphone)) {
        this.$message({
          message: "请输入正确手机号!",
          type: "warning",
          offset: 150,
        });
      } else {
        // sendCodeLogin({
        //   phone: iphone,
        // }).then(() => {
          this.countDown(60);
        // });
      }
    },
    //验证码倒计时
    countDown(time) {
      let _this = this;
      time--;
      if (time == 0) {
        _this.code = "获取验证码";
        return;
      }
      setTimeout(function () {
        _this.code = "已发送("+time + ")秒";
        _this.countDown(time);
      }, 1000);
    },


    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 });
            Cookies.set("password", encrypt(this.loginForm.password), {
              expires: 30,
            });
            Cookies.set("rememberMe", this.loginForm.rememberMe, {
              expires: 30,
            });
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove("rememberMe");
          }
          this.$store
            .dispatch("Login", this.loginForm)
            .then(() => {
              this.$router.push({ path: this.redirect || "/" }).catch(() => {});
            })
            .catch(() => {
              this.loading = false;
              if (this.captchaEnabled) {
                this.getCode();
              }
            });
        }
      });
    },

    handlePage(path){
      this.$router.push({path})
    }
  },
};
</script>

<style lang="scss" scoped>
@import '@/assets/styles/login.scss';
.logintitle{
  color: rgba(0,0,0,.85);
}
.yzmitem{
  position: relative;
  .reg_tips{
    white-space: nowrap;
    color: #999;
    position: absolute;
    left: 340px;
  }
}
</style>
